package com.xyz.mockapi.mainlineorder.controller;

import com.xyz.mockapi.common.entity.BdSubProductTypeEntity;
import com.xyz.mockapi.common.entity.OnlineBomList;
import com.xyz.mockapi.common.entity.OnlineProductEntity;
import com.xyz.mockapi.common.pojo.dto.*;
import com.xyz.mockapi.mainlineorder.service.BdSubProductTypeService;
import com.xyz.mockapi.mainlineorder.service.OnlineBomService;
import com.xyz.mockapi.mainlineorder.service.OnlineProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/eds2b-outer-api/outer/product")
public class ProductOnlineController {

    private final OnlineProductService onlineProductService;
    private final OnlineBomService onlineBomService;
    private final BdSubProductTypeService bdSubProductTypeService;

    public ProductOnlineController(
            OnlineProductService onlineProductService,
            OnlineBomService onlineBomService,
            BdSubProductTypeService bdSubProductTypeService) {
        this.onlineProductService = onlineProductService;
        this.onlineBomService = onlineBomService;
        this.bdSubProductTypeService = bdSubProductTypeService;
    }

    @PostMapping("/productOnline")
    public ProductOnlineResponse productOnline(@RequestBody ProductOnlineRequest request) {
        // 1. 身份验证
        if (!"emes".equals(request.getRequestUserName()) || !"Emes@admin".equals(request.getRequestUserPwd())) {
            return buildErrorResponse(500, "身份验证失败");
        }

        // 2. 查询所有有效工单（取第一条）
        List<OnlineProductEntity> allProductList = onlineProductService.list();
        if (allProductList == null || allProductList.isEmpty()) {
            return buildErrorResponse(502, "当前没有投产的工单，请稍后再试");
        }
        OnlineProductEntity productEntity = allProductList.get(0);

        // 3. 组装数据：实体转无idDTO
        ProductOnlineResponse.Data data = new ProductOnlineResponse.Data();

        // 3.1 BOM列表：OnlineBomList（含id）→ OnlineBomDTO（无id）
        List<OnlineBomList> bomEntityList = onlineBomService.listByItemcode(productEntity.getFItemcode());
        if (bomEntityList == null || bomEntityList.isEmpty()) {
            return buildErrorResponse(501, "工单[" + productEntity.getFProductplanname() + "]未维护BOM，请联系MES管理员");
        }
        List<OnlineBomDTO> bomDTOList = bomEntityList.stream().map(bomEntity -> {
            OnlineBomDTO bomDTO = new OnlineBomDTO();
            BeanUtils.copyProperties(bomEntity, bomDTO); // 自动忽略id（DTO无id字段）
            return bomDTO;
        }).collect(Collectors.toList());
        data.setOnlineBomList(bomDTOList);

        // 3.2 工单主体：OnlineProductEntity（含id）→ OnlineProductDTO（无id）
        OnlineProductDTO productDTO = new OnlineProductDTO();
        BeanUtils.copyProperties(productEntity, productDTO);
        data.setOnlineProductEntity(productDTO);

        // 3.3 打刻配置：BdSubProductTypeEntity（含id）→ BdSubProductTypeDTO（无id）
        List<BdSubProductTypeEntity> subProductTypeEntityList = bdSubProductTypeService.listByProductId(productEntity.getId());
        if (subProductTypeEntityList == null || subProductTypeEntityList.isEmpty()) {
            return buildErrorResponse(500, "工单[" + productEntity.getFProductplanname() + "]产品平台信息缺失");
        }
        BdSubProductTypeDTO subProductTypeDTO = new BdSubProductTypeDTO();
        BeanUtils.copyProperties(subProductTypeEntityList.get(0), subProductTypeDTO);
        data.setBdSubProductTypeEntity(subProductTypeDTO);

        // 4. 构造响应
        ProductOnlineResponse response = new ProductOnlineResponse();
        response.setMessage("操作成功！");
        response.setCode(200);
        response.setData(data);
        return response;
    }

    // 辅助方法：构建错误响应
    private ProductOnlineResponse buildErrorResponse(int code, String message) {
        ProductOnlineResponse response = new ProductOnlineResponse();
        response.setMessage(message);
        response.setCode(code);
        response.setData(null);
        return response;
    }
}